package com.knife.news.manage.action;

import java.awt.event.MouseAdapter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Collection;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSON;
import net.sf.json.JSONArray; 
import net.sf.json.JsonConfig;

import org.hibernate.hql.ast.tree.FromClause;
import org.junit.Test;

import com.knife.member.Userinfo;
import com.knife.news.logic.FieldsService;
import com.knife.news.logic.FormService;
import com.knife.news.logic.SiteService;
import com.knife.news.logic.Type2Service;
import com.knife.news.logic.TypeService;
import com.knife.news.logic.impl.FieldsServiceImpl;
import com.knife.news.logic.impl.FlowNodeServiceImpl;
import com.knife.news.logic.impl.FormServiceImpl;
import com.knife.news.logic.impl.NewsServiceImpl;
import com.knife.news.logic.impl.SiteServiceImpl;
import com.knife.news.logic.impl.Type2ServiceImpl;
import com.knife.news.logic.impl.TypeServiceImpl;
import com.knife.news.logic.impl.UserServiceImpl;
import com.knife.news.logic.impl.FlowServiceImpl;
import com.knife.news.model.Form;
import com.knife.news.object.Flow;
import com.knife.news.object.FlowNode;
import com.knife.news.object.FormField;
import com.knife.news.object.Site;
import com.knife.news.object.Type;
import com.knife.news.object.News;
import com.knife.news.object.Type2;
import com.knife.news.object.User;

import com.knife.util.CommUtil;
import com.knife.web.ActionContext;
import com.knife.web.Module;
import com.knife.web.Page;
import com.knife.web.WebForm;
import com.sun.star.sdbc.SQLException;
//import com.sun.jndi.url.corbaname.corbanameURLContextFactory;

public class FlowNodeManageAction extends ManageAction  {
	private FlowNodeServiceImpl flowNodeDao = FlowNodeServiceImpl.getInstance();
	private UserServiceImpl userDao = UserServiceImpl.getInstance();
	private FlowServiceImpl flowDao = FlowServiceImpl.getInstance();
	private TypeServiceImpl typeDao = TypeServiceImpl.getInstance();
	private TypeService typeDAO = TypeServiceImpl.getInstance();
	private NewsServiceImpl newDao = NewsServiceImpl.getInstance();
	private Type2Service type2DAO = Type2ServiceImpl.getInstance();
	private SiteService siteDAO = SiteServiceImpl.getInstance();
	private FormService formDAO = FormServiceImpl.getInstance();
	private FieldsService fieldsDAO = FieldsServiceImpl.getInstance();
	private String flow = "";
	
	private String sid = "";
	
	private UserServiceImpl manageusersDAO = UserServiceImpl.getInstance();
	List<User> manageusers = manageusersDAO.getAllUsers();
	
	public Page doInit(WebForm form, Module module){
		return module.findPage("index");
	}
	
	public Page doList(WebForm form,Module module) {
		if(sid.equals("")){
			sid = CommUtil.null2String(form.get("sid"));
		}
		if(flow.equals("")){
			flow = CommUtil.null2String(form.get("workflow_id"));
		}
		int pop=0;
		int step=1;
		List<FlowNode> allFlowNodes = flowNodeDao.getFlowNodeByFlowId(flow);
		if(allFlowNodes.isEmpty()){
			com.knife.news.model.FlowNode obj=new com.knife.news.model.FlowNode();
			FlowNode beginNode= new FlowNode(obj); 
			FlowNode  endNode = new FlowNode(obj);
			try{
				beginNode.setWorkflow_id(flow);
			}catch(Exception e){
				e.getCause();
			};
			beginNode.setType(0);
			beginNode.setStep(step);
			beginNode.setStatus(0);
			beginNode.setName("Begin");
			try {
				flowNodeDao.saveFlowNode(beginNode);
				List<FlowNode> begin= flowNodeDao.getFlowNodeByFlowId(flow);
				
				if(begin.size()>0){
					if(begin.get(0).getId()==""||begin.get(0).getId()==null){
						throw new SQLException("begin.get(0).getId()  is null");
					}
					endNode.setPrev_node(begin.get(0).getId());
					endNode.setWorkflow_id(flow);
					endNode.setStep(2);
					endNode.setName("End");
				flowNodeDao.saveFlowNode(endNode);
				}
				else{
					throw new SQLException("ddddddd"+begin.size());
				}
			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
			}
			
		}else{
			 step=allFlowNodes.size();
			//allFlowNodes.get(allFlowNodes.size()).setStep(step+1);
		}
		int rows=0;
		if(allFlowNodes!=null)	{
			rows = allFlowNodes.size();// 总数
		}
		int pageSize = 18;// 每页18条
		int currentPage = 1;
		int frontPage = 0;
		int nextPage = currentPage+1;
		List<FlowNode> firstFlowNodes = new ArrayList<FlowNode>();
		int totalPage = (int) Math.ceil((float) (rows) / (float) (pageSize));// 计算页数
		Collection<Object> paras = new ArrayList<Object>();
		if(flow.length()>0){
			//paras.add(sid);
			paras.add(flow);
			form.addResult("workflow_id", flow);
			firstFlowNodes = flowNodeDao.getFlowNodeBySql("k_workflow_id=? order by k_step asc",paras,0,pageSize);
		}else{
			firstFlowNodes = flowNodeDao.getFlowNodeBySql("1=1 order by k_step asc",paras,0,pageSize);
		}
//		Flow thisflow = flowDao.getFlowById(flow);
//		form.addResult("thisFlow", thisflow);
		form.addResult("workflow_id", flow);
		
		form.addResult("rows", rows);
		form.addResult("currentPage", currentPage);
		form.addResult("pageSize", pageSize);
		form.addResult("frontPage", frontPage);
		form.addResult("nextPage", nextPage);
		form.addResult("totalPage", totalPage);
		form.addResult("UList", manageusers);
		//form.addResult("step", step);
		form.addResult("flowNodeList", firstFlowNodes);
		form.addResult("flowNodeDao", flowNodeDao);
		form.addResult("pop", pop);
		
		
		return module.findPage("list");
	}
	
	public Page doPage(WebForm form, Module module) {
		if(sid.equals("")){
			sid = CommUtil.null2String(form.get("sid"));
		}
		if(flow.equals("")){
			flow = CommUtil.null2String(form.get("workflow_id"));
		}
		List<FlowNode> allFlowNodes = flowNodeDao.getFlowNodeByFlowId(flow);
		int rows = allFlowNodes.size();
		int pageSize = 18;
		int paraPage = CommUtil.null2Int(form.get("page"));
		int frontPage = paraPage - 1;
		int nextPage = paraPage + 1;
		int totalPage = (int) Math.ceil((float) rows / (float) pageSize);
		int begin = (paraPage - 1) * pageSize + 1;
		int end = rows - begin + 1;
		Collection<Object> paras = new ArrayList<Object>();
		List<FlowNode> flowNodeList = new ArrayList<FlowNode>();
		form.addResult("frontPage", frontPage);
		form.addResult("nextPage", nextPage);
		String sql="";
		if(flow.length()>0){
			paras.add(flow);
			form.addResult("workflow_id", flow);
			sql="k_workflow_Id=? order by k_step desc";
		}else{
			sql="1=1";
		}
		if (end < pageSize) {
			flowNodeList = flowNodeDao.getFlowNodeBySql(sql, paras, begin - 1, end);
		} else {
			flowNodeList = flowNodeDao.getFlowNodeBySql(sql, paras, begin - 1, pageSize);
		}
		Flow thisflow = flowDao.getFlowById(flow);
		form.addResult("thisFlow", thisflow);
		form.addResult("currentPage", paraPage);
		form.addResult("totalPage", totalPage);
		form.addResult("rows", rows);
		form.addResult("flowNodeList", flowNodeList);
		form.addResult("UList", manageusers);
		return module.findPage("list");
	}
	
	
	//发文工作流
	public Page doSave(WebForm form, Module module) {
		FlowNode flowNode = (FlowNode)form.toPo(FlowNode.class);
		String flow = CommUtil.null2String(form.get("workflow_id"));
		
		flowNode.setStep(0);
		flowNodeDao.saveFlowNode(flowNode);
		
		List<FlowNode> nodeList = new ArrayList<FlowNode>();
		List<FlowNode> current = new ArrayList<FlowNode>();
		
		Collection<Object> paras = new ArrayList<Object>();
		Collection<Object> cparas = new ArrayList<Object>();
		
		if(flow.length()>0){
			paras.add(flow);
			
			cparas.add(flow);
			cparas.add(0);
			form.addResult("workflow_id", flow);
			nodeList = flowNodeDao.getFlowNodeBySql("k_workflow_id=? order by k_step desc",paras,0,-1);//升序是asc
			current = flowNodeDao.getFlowNodeBySql("k_workflow_id=? and k_step=? order by k_step desc",cparas,0,-1);
		}
		
			try {
				if(!current.isEmpty()){
					int endindex = nodeList.size()-1;
					FlowNode endnode = nodeList.get(0);
					FlowNode curnode = current.get(0);
					FlowNode prenode =flowNodeDao.getPrevFlowNode(endnode);
					
					curnode.setPrev_node(endnode.getPrev_node());
					curnode.setNext_node(endnode.getId());
					curnode.setStep(endindex);
					
					prenode.setNext_node(curnode.getId());
					
					endnode.setStep(endindex+1);
					endnode.setPrev_node(curnode.getId());
					
					flowNodeDao.updateFlowNode(prenode);
					flowNodeDao.updateFlowNode(curnode);
					flowNodeDao.updateFlowNode(endnode);
				}else{
				throw new Exception();
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				
			}
	
		form.addResult("workflow_id", flow);
		
		return doList(form, module);
		
	}
	
	public Page doSave1(WebForm form, Module module) {
		FlowNode flowNode = (FlowNode)form.toPo(FlowNode.class);
		String flow = CommUtil.null2String(form.get("workflow_id"));
		
		String sqlString = "k_workflow_id=? order by k_step desc";
		
		//String init_function ="";
		FlowNode prevnode = null;
		int step = 0;
		//String run_function = "";
		
		List<FlowNode> flowNodeList = new ArrayList<FlowNode>();
		Collection<Object> paras = new ArrayList<Object>();
		if(flow.length()>0){
			paras.add(flow);
		}
		flowNodeList = flowNodeDao.getFlowNodeBySql(sqlString, paras, 0, -1);
		
		if(flowNode.getName()!="开始" && flowNode.getName()!="结束"){
			if(flowNodeList != null){
				prevnode = flowNodeList.get(0);
				prevnode.setNext_node(flowNode.getId());
				step = prevnode.getStep()+1;
				flowNode.setStep(step);
				flowNode.setPrev_node(prevnode.getId());
				//run_function = "/manage_flow.ad/parameter=run";
				//flowNode.setRunFunction(run_function);
				
			}else{
				//这个也应该直接在页面中选择吧，
	//			init_function = "/manage_flow.ad/parameter=initFunction";
	//			flowNode.setInitFunction(init_function);
			}
	
		}
		if (flowNodeDao.saveFlowNode(flowNode)) {
			form.addResult("msg", "添加成功！");
			return doList(form, module);
			
		} else {
			return doList(form, module);
		}
	}
	
	public Page doAdd(WebForm form,Module module ){
		String flow = CommUtil.null2String(form.get("workflow_id"));
		String nodeid = CommUtil.null2String(form.get("id"));
		FlowNode flowNode = flowNodeDao.getFlowNodeById(nodeid);
		form.addResult("flowNode", flowNode);
	    form.addResult("workflow_id", flow);
	    form.addResult("action", "save");
	    form.addResult("UList", manageusers);
		return module.findPage("add");
	}
	
	public Page doEdit(WebForm form,Module module ){
		String flow = CommUtil.null2String(form.get("workflow_id"));
		String nodeid = CommUtil.null2String(form.get("id"));
		FlowNode flowNode = flowNodeDao.getFlowNodeById(nodeid);
		form.addResult("flowNode", flowNode);
		form.addResult("workflow_id", flow);
		form.addResult("action", "update");
		form.addResult("UList", manageusers);
		return module.findPage("add");
	}

	public Page doUpdate(WebForm form, Module module) {
		FlowNode flowNode = (FlowNode) form.toPo(FlowNode.class);
		String id = CommUtil.null2String(form.get("id"));
		FlowNode flow=flowNodeDao.getFlowNodeById(id);
		flowNode.setStep(flow.getStep());
		flowNode.setPrev_node(flow.getPrev_node());
		flowNode.setNext_node(flow.getNext_node());

		if (flowNodeDao.updateFlowNode(flowNode)) {
			form.addResult("msg", "编辑成功！");
			return doList(form, module);
		} else {
			return doList(form, module);
		}
	}
	
	
	public  JSON doGetObjNode(String nodeid)  {
		//String nodeid = CommUtil.null2String(form.get("nodeid"));
		
		FlowNode flowNode = flowNodeDao.getFlowNodeById(nodeid);
		
         List<Object> node_json = new ArrayList();
         node_json.add(flowNode.getId());
         node_json.add(flowNode.getName());
         node_json.add(flowNode.getType());
         node_json.add(flowNode.getExecutor());
         node_json.add(flowNode.getExecute_type());
         //node_json.add(e);
         try{
        	 JSON json=JSONArray.fromObject(node_json);
        	 System.out.println(json);
         }catch(Exception e){
        	 e.getStackTrace();
         }
         return JSONArray.fromObject(node_json);
	}
	
	public Page doDesign(WebForm form,Module module ){
		String nodeid = CommUtil.null2String(form.get("nodeid"));
		FlowNode flowNode = flowNodeDao.getFlowNodeById(nodeid);
		form.addResult("action", "update");
		form.addResult("UList", manageusers);
		return module.findPage("edit");
	}
	
	public Page doDelete(WebForm form,Module module ){
		String nodeid = CommUtil.null2String(form.get("id"));
		String flow = CommUtil.null2String(form.get("workflow_id"));
		
		FlowNode flowNode = flowNodeDao.getFlowNodeById(nodeid);
		FlowNode prevnode= flowNodeDao.getPrevFlowNode(flowNode);
		FlowNode nextnode= flowNodeDao.getNextFlowNode(flowNode);
		if(prevnode==null||prevnode.equals("")){
			form.addResult("msg", "这是开始流节点，不允许删除！");
		}else{
			if(nextnode==null||nextnode.equals("")){
				form.addResult("msg", "这是结束流节点，不允许删除！");
			}else{
				prevnode.setNext_node(nextnode.getId());
				flowNodeDao.updateFlowNode(prevnode);
				
				nextnode.setPrev_node(prevnode.getId());
				flowNodeDao.updateFlowNode(nextnode);
				
				
				List<FlowNode> nodeList = new ArrayList<FlowNode>();
				Collection<Object> paras = new ArrayList<Object>();
				if(flow.length()>0){
					paras.add(flow);
				}
				String id=flowNode.getNext_node();
				int step=flowNode.getStep();
				nodeList = flowNodeDao.getFlowNodeBySql("k_workflow_id=? order by k_step asc",paras,0,-1);//升序是asc
				for(int i=flowNode.getStep(); i<=nodeList.size()-1;i++){
					
					FlowNode node=flowNodeDao.getFlowNodeById(id);
					node.setStep(node.getStep()-1);
					flowNodeDao.updateFlowNode(node);
					id=node.getNext_node();
				}
				flowNodeDao.delFlowNode(flowNode);
				form.addResult("msg", "删除成功！");
			}
		}
		
		
		form.addResult("workflow_id", flow);
		return doList(form , module);
	}
	
	//
	public void doInitFunction(WebForm form , Module module){
		doChangeStatus(form, module);
	}
	
	public Page doChangeStatus(WebForm form,Module module){
		String nodeid = CommUtil.null2String("nodeid");
		FlowNode currentnode = flowNodeDao.getFlowNodeById(nodeid);
		if (currentnode.getNext_node() != null) {
			currentnode.setStatus(1);
			if (flowNodeDao.saveFlowNode(currentnode)) {
				form.addResult("msg", "该节点成功执行完毕！");
			}
			FlowNode nextnode = flowNodeDao.getNextFlowNode(currentnode);
			if (nextnode != null) {
				nodeid = nextnode.getId();
				form.addResult("msg", "已经指向下一个流节点。");

			} else {
				doEndFunction(form, module);
			}
		}else {
			form.addResult("msg", "该流程序成功启动。");
		}
		return module.findPage("ajax");
	}
	
	public void doEndFunction(WebForm form , Module module){
		
		form.addResult("mag", "该流程序成功执行完毕！");
	
	}
	
	public Page doPopNews( WebForm form , Module module){
		String admin = CommUtil.null2String("admin");
		String tid="";
		String treenews = "";
		
		
		//发布文章
		tid = CommUtil.null2String(form.get("tid"));
		treenews = CommUtil.null2String(form.get("treenews"));
		List<Type> typeList = new LinkedList<Type>();
		List<Type2> type2List = type2DAO.getAllTypes();
		if (!tid.equals("")) {
			// 输出自定义表单
			Type aType = typeDAO.getTypeById(tid);
			if(aType.getSite()!=null){
				Site site = siteDAO.getSiteById(aType.getSite());
				if(site!=null){
				
					if(site.getHtml()==1){
					
						ActionContext.getContext().getSession().setAttribute("site_dir", site.getPub_dir());
						if(site.getBig5()==1){
							
							ActionContext.getContext().getSession().setAttribute("big5_dir", site.getPub_dir()+"/big5");
						}
					}
					form.addResult("thisSite", site);
				}
			}
			if (popedom > 0) {
				typeList = typeDAO.getSubTypesById(aType.getParent());
			} else {
				typeList = typeDAO.getRightSubTypesById(aType.getParent(),
						user.getId());
			}
			if (aType.getForm() != null) {
				String formId = aType.getForm();
				if (formId.length() > 0) {
					try{
						Form aform = formDAO.getFormById(formId);
					
						List<FormField> formFields = fieldsDAO.jsonStringToList("0", aform.getContent());
						form.addResult("fieldList", formFields);
					}catch(Exception e){
						System.out.println("自定义表单查找异常:"+e.getMessage());
					}
				}
			}
			form.addResult("tid", tid);
			form.addResult("tname", aType.getName());
		}
		doChangeStatus(form, module);
		return module.findPage("ajax");
	}
	
	public Page doCredit( WebForm form , Module module){
		//审核文章
		String admin = CommUtil.null2String("admin");
		String sql = "k_admin = "+admin +"and k_display = 0";
		List<News> news = new ArrayList<News>();
		Collection<Object> paras = new ArrayList<Object>();
		news = newDao.getNewsBySql(sql, paras, 0, -1);
		
		for( News anew : news ){
			anew.setDisplay(1);
			if(newDao.saveNews(anew)){
			form.addResult("msg", "审核成功");
			}
		}
		doChangeStatus(form, module);
		return module.findPage("ajax");
	}
	
	
	
}
